// pages/publish/publish.js
var app = getApp()
var host_url = require('../../config/api.js')
var COS = require('../../utils/cos-wx-sdk-v5.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    image_list: ["../../static/picture.jpg"],
    content: null,
    push_image_list: [],
  },
  click_push() {
    this.up_load_file(this.push_sns)
  },
  //发布动态方法
  push_sns() {
    wx.request({
      url: host_url.host_url + '/api/mini/create_sns',
      method: 'POST',
      data: {
        'token': app.globalData.userInfo.token,
        'type': 2,
        'content': this.data.content,
        'image_list': this.data.push_image_list,
        'openid': app.globalData.openid
      },
      success: res => {
        this.setData({    
        image_list: ["../../static/picture.jpg"],
        content: null,
        push_image_list: [],
      })
      }
    })
  },
  //上传图片的方法
 async up_load_file(callback) {
    var that = this
    // 获取腾讯云临时密钥
    var cos = new COS({
      // 必选参数
      getAuthorization: function (options, callback) {
        wx.request({
          url: 'http://127.0.0.1:8000/api/mini/credential',
          data: {
            // 可从 options 取需要的参数
          },
          success: function (result) {
            var data = result.data;
            var credentials = data && data.credentials;
            if (!data || !credentials) return console.error('credentials invalid');
            callback({
              TmpSecretId: credentials.tmpSecretId,
              TmpSecretKey: credentials.tmpSecretKey,
              // v1.2.0之前版本的sdk使用XCosSecurityToken而不是SecurityToken
              // 本来无法上传报错authorization error， 后来把SecurityToken改为XCosSecurityToken后好了
              XCosSecurityToken: credentials.sessionToken,
              StartTime: data.startTime,
              ExpiredTime: data.expiredTime,
            });
          }
        });
      }
    });
    // 去掉最后一个加号图片
    var new_image_list = this.data.image_list.slice(0, -1) 
    for (var index in new_image_list) {
      var filePath = new_image_list[index]
      cos.postObject({
        Bucket: 'lightweightbaby-1259544235',
        Region: 'ap-nanjing',
        Key: Date.now() + '.png',
        FilePath: filePath,
        onProgress: function (info) {}
      }, function (err, data) {
        // console.log(err || data)
        if (data != null) {
          var fileCosFilePath = data.Location; //上传成功之后，返回路径信息，用于后台存库
          that.data.push_image_list.push('https://' + fileCosFilePath)
          if (index == that.data.push_image_list.length - 1) {
            callback()
          }
        }
      });
    }

  },

  //双向绑定输入的值
  textinput(e) {
    this.setData({
      content: e.detail.value
    })
  },
  add_image() {
    wx.chooseImage({
      count: 9,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: res => {
        this.setData({
          // image_list: this.data.image_list.concat(res.tempFilePaths)
          image_list: res.tempFilePaths.concat(this.data.image_list)
          
        })
        console.log('选择图片后的',this.data.image_list)
      } 
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})